package link.hwx.util;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class UnzipUtil {
    public static void main(String[] args) {
        String zipFilePath = "F:\\demo\\1.zip";
        String destDirectory = "F:\\demo";
        unzip(zipFilePath, destDirectory);
        try {
            String  strurl = zipFilePath.substring(zipFilePath.lastIndexOf("\\")+1, zipFilePath.lastIndexOf("."));
            String basestr = Base64Util.fileToBase64Str(new File(destDirectory+"\\"+strurl+".pdf"));
            System.out.println(strurl);
           new File(destDirectory+"\\"+strurl+".pdf").delete();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String unzip(String zipFilePath, String destDirectory) {
        File destDir = new File(destDirectory);
        if (!destDir.exists()) {
            destDir.mkdir();
        }
        String fileName = "";
        try (ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath))) {
            ZipEntry entry = zipIn.getNextEntry();

            // 遍历 ZIP 文件中的每个条目
            while (entry != null) {
                fileName = entry.getName();
                String filePath = destDirectory + File.separator + entry.getName();
                if (!entry.isDirectory()) {
                    // 如果是文件，则解压文件
                    extractFile(zipIn, filePath);
                } else {
                    // 如果是目录，则创建目录
                    File dir = new File(filePath);
                    dir.mkdir();
                }

                zipIn.closeEntry();
                entry = zipIn.getNextEntry();

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }


    private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
        try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath))) {
            byte[] bytesIn = new byte[4096];
            int read;
            while ((read = zipIn.read(bytesIn)) != -1) {
                bos.write(bytesIn, 0, read);
            }
        }
    }
}